package top.deepdesigner.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import top.deepdesigner.pojo.DtsAd;
import top.deepdesigner.service.DtsAdService;

import java.util.Date;
import java.util.List;

/**
 * Start up <br/>
 * Created with IntelliJ IDEA. <br/>
 * Project Name: shop_manage <br/>
 * Author: duanruiqing <br/>
 * DateTime: 2022/9/24 星期六 15:54:38 <br/>
 */
@Service
public class DtsAdServiceImpl extends ServiceImpl<BaseMapper<DtsAd>, DtsAd> implements DtsAdService {
  @Override
  public Long getAdCount() {
    return this.count(new LambdaQueryWrapper<DtsAd>().eq(DtsAd::getDeleted, false));
  }

  @Override
  public List<DtsAd> getAdList(Integer page, Integer limit, String sort, String order, String name, String content) {
    QueryWrapper<DtsAd> wrapper = new QueryWrapper<>();
    wrapper.eq(true, "deleted", false)
        .like(!StringUtils.isEmpty(name), "name", name)
        .like(!StringUtils.isEmpty(content), "content", content)
        .orderBy(!StringUtils.isEmpty(sort), "asc".equalsIgnoreCase(order), sort);
    return this.page(new Page<>(page, limit), wrapper).getRecords();

  }

  @Override
  @Transactional
  public DtsAd createAd(DtsAd ad) {
    List<DtsAd> list = this.list(new LambdaQueryWrapper<DtsAd>().eq(DtsAd::getDeleted, false).eq(DtsAd::getName, ad.getName()));
    if (list.size() > 0) {
      return null;
    }
    ad.setAddTime(new Date());
    ad.setUpdateTime(new Date());
    ad.setDeleted(false);
    this.save(ad);
    return ad;
  }

  @Override
  public DtsAd getAdById(Integer id) {
    LambdaQueryWrapper<DtsAd> wrapper = new LambdaQueryWrapper<>();
    wrapper.eq(DtsAd::getId, id);
    return this.getOne(wrapper);
  }

  @Override
  @Transactional
  public DtsAd updateAd(DtsAd ad) {
    ad.setUpdateTime(new Date());
    LambdaQueryWrapper<DtsAd> wrapper = new LambdaQueryWrapper<>();
    wrapper.eq(DtsAd::getId, ad.getId());
    this.update(ad, wrapper);
    return ad;
  }

  @Override
  @Transactional
  public void deleteAd(DtsAd ad) {
    ad.setDeleted(true);
    LambdaQueryWrapper<DtsAd> wrapper = new LambdaQueryWrapper<>();
    wrapper.eq(DtsAd::getId, ad.getId());
    this.update(ad, wrapper);
  }
}
